import { useState } from 'react';
import './Order.css';
import orderApi from '@/apis/orderApi';
import { Checkbox, Empty, List, PullRefresh, Tabs, Image, Stepper, Button } from 'react-vant';
import OrderCard from '@/components/OrderCard';
import CustomOverlay from '@/components/CustomerOverlay';
import { debounceAsync, getGoodsImagePath, promptResult } from '@/utils/common';
import MyPromotePrice from '@/components/MyPromotePrice';

const limit = 10;
const statussData = [[2], [0, 1], [3, 4, -1, -2, -3, -4, -5]];

const Order: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [orders, setOrders] = useState<ResponseOrdersDto[]>([]);
  const [currentOrder, setCurrentOrder] = useState<ResponseOrdersDto>();
  const [active, setActive] = useState(0);
  const [page, setPage] = useState(1);
  const [finished, setFinished] = useState(false);
  const [visible, setVisible] = useState(false);
  const [checkedIds, setCheckedIds] = useState<number[]>([]);

  const loadMore = async () => {
    const res: ResponseApiDto = await orderApi.getPagination(
      page,
      limit,
      undefined,
      statussData[active]
    );
    if (res.status >= 0) {
      setOrders([...orders, ...res.data.data]);
      setPage((prev) => prev + 1);
      if (res.data.data.length < limit) {
        setFinished(true);
      }
    }
    if (loading) setLoading(false);
  };

  const onRefresh = async () => {
    setLoading(true);
    const res: ResponseApiDto = await orderApi.getPagination(
      page,
      limit,
      undefined,
      statussData[active]
    );
    if (res.status >= 0) {
      setOrders([...orders, ...res.data.data]);
      setPage((prev) => prev + 1);
      if (res.data.data.length < limit) {
        setFinished(true);
      }
    }
    setLoading(false);
  };

  const handleAcceptOrder = async (orderId: number) => {
    setVisible(true);
    setCurrentOrder(JSON.parse(JSON.stringify(orders.find((d) => d.id === orderId)!)));
    setCheckedIds(orders.find((d) => d.id === orderId)!.details.map((d) => d.id));
  };

  const sureAcceptOrder = async () => {
    let orderDetails: ResponseOrderDetailDto[] = currentOrder!.details.filter((d) =>
      checkedIds.includes(d.id)
    );
    promptResult(
      orderApi.acceptOrder({
        id: currentOrder!.id,
        odids: orderDetails.map((d) => d.id),
        counts: orderDetails.map((d) => d.count),
      }),
      () => {},
      () => {
        setVisible(false);
        setOrders(orders.filter((d) => d.id != currentOrder!.id));
      }
    );
  };

  const handleTabsChange = debounceAsync(async (i: number) => {
    setOrders([]);
    setPage(1);
    setActive(i);
    setFinished(false);
  }, 100);

  const handleCheckAll = (checked: boolean) => {
    if (checked) {
      setCheckedIds(currentOrder!.details.map((d) => d.id));
    } else {
      setCheckedIds([]);
    }
  };

  const sumPrice = () => {
    let sum = 0;
    currentOrder?.details
      .filter((d) => checkedIds.includes(d.id))
      .forEach((d) => (sum += d.count * (d.promotePrice ? d.promotePrice : d.price)));
    return sum.toFixed(2);
  };

  return (
    <>
      <Tabs
        type="card"
        active={active}
        onChange={(_, i) => handleTabsChange.call(handleTabsChange, i)}
      >
        <Tabs.TabPane title="待收货"></Tabs.TabPane>
        <Tabs.TabPane title="待发货"></Tabs.TabPane>
        <Tabs.TabPane title="已完成"></Tabs.TabPane>
      </Tabs>
      <PullRefresh onRefresh={onRefresh}>
        <List onLoad={loadMore} finished={finished} finishedText="没有更多了">
          {loading || orders.length > 0 ? (
            orders.map((order) => (
              <OrderCard key={order.id} order={order} onAcceptOrder={handleAcceptOrder} />
            ))
          ) : (
            <Empty />
          )}
        </List>
      </PullRefresh>
      <CustomOverlay
        visible={visible}
        width={'80vw'}
        height={'70vh'}
        showCloseButton={true}
        onClose={() => setVisible(false)}
      >
        {currentOrder?.details.map((e) => (
          <div key={e.id} className="good-item">
            <div className="checkbox">
              <Checkbox
                checked={checkedIds.includes(e.id)}
                iconSize="28px"
                onChange={(checked) => {
                  if (checked) setCheckedIds([...checkedIds, e.id]);
                  else setCheckedIds(checkedIds.filter((d) => d != e.id));
                }}
              />
            </div>
            <div className="image">
              <Image src={getGoodsImagePath(e.goodId, e.photo)} />
            </div>
            <div className="info">
              <div className="info-item">{e.name + ' ' + e.specs}</div>
              <div className="info-item">
                <MyPromotePrice price={e.price} propmotePrice={e.promotePrice} />
              </div>
              <div className="info-item" style={{ display: 'flex', width: '100%' }}>
                <div style={{ marginLeft: 'auto' }}>
                  <Stepper
                    value={e.count}
                    min={0}
                    max={
                      orders
                        .find((d) => d.id === currentOrder.id)
                        ?.details.find((d) => d.id === e.id)?.count
                    }
                    onPlus={() => {
                      setCurrentOrder((prev: any) => {
                        return {
                          ...prev,
                          details: [
                            ...prev.details.map((d: ResponseOrderDetailDto) => {
                              if (d.id === e.id) {
                                d.count++;
                              }
                              return d;
                            }),
                          ],
                        };
                      });
                    }}
                    onMinus={() => {
                      setCurrentOrder((prev: any) => {
                        return {
                          ...prev,
                          details: [
                            ...prev.details.map((d: ResponseOrderDetailDto) => {
                              if (d.id === e.id) {
                                d.count--;
                              }
                              return d;
                            }),
                          ],
                        };
                      });
                    }}
                    onBlur={(event) =>
                      setCurrentOrder((prev: any) => {
                        return {
                          ...prev,
                          details: [
                            ...prev.details.map((d: ResponseOrderDetailDto) => {
                              if ((d.id = e.id)) {
                                if (
                                  parseInt(event.target.value) >= 0 &&
                                  parseInt(event.target.value) <=
                                    orders
                                      .find((d) => d.id === currentOrder.id)!
                                      .details.find((d) => d.id === e.id)!.count
                                )
                                  d.count = parseInt(event.target.value);
                              }
                              return d;
                            }),
                          ],
                        };
                      })
                    }
                  />
                </div>
              </div>
            </div>
          </div>
        ))}
        <div
          style={{ display: 'flex', gap: '30px', justifyContent: 'center', alignItems: 'center' }}
        >
          <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
            <Checkbox
              checked={(() => {
                return currentOrder && currentOrder.details.length === checkedIds.length;
              })()}
              iconSize={28}
              onChange={handleCheckAll}
            />
            全选
          </div>
          <div>
            合计：<span className="sum-price">¥{sumPrice()}</span>
          </div>
          <div>
            <Button round type="danger" onClick={sureAcceptOrder}>
              确认
            </Button>
          </div>
        </div>
      </CustomOverlay>
    </>
  );
};

export default Order;
